//
// Created by xdc on 2025/11/7.
//

#include "back_admin.h"

//登陆
int back_admin_login(){
    printf("后端管理员登录!\n");
    BackAdmin admin;
    printf("输入管理员名:");
    scanf("%s",admin.adminname);
    printf("输入密码:");
    scanf("%s",admin.password);
    //查询该账号是否存在
    //定义查询sql
    //select * from front_user where username=? and password=?;
    //select count(*) from front_user where username=? and password=?;
    const char * sql =
            "select count(*) from admin_user where account=? and password=?";
    //定义预编译语句句柄
    sqlite3_stmt * stmt;
    int rc = sqlite3_prepare_v2(db,sql,-1,&stmt,NULL);
    if(rc!=SQLITE_OK){
        fprintf(stderr,"back_admin_login:编译出错!\n");
        return -1;
    }
    //绑定参数: 注意?位置，从1开始
    sqlite3_bind_text(stmt,1,admin.adminname,-1,SQLITE_TRANSIENT);
    sqlite3_bind_text(stmt,2,admin.password,-1,SQLITE_TRANSIENT);
    //执行查询:在表中读一次记录，会返回读取的状态:
    // SQLITE_ROW 说明读取到了，此时就可以获取改行的值
    // SQLITE_DONE 或者其他状态 说明没读取到，就不能去获取值

    rc = sqlite3_step(stmt);
    //查询的行数
    int rowcount = 0;
    //读取到一行数据
    if(rc==SQLITE_ROW){
        //获取改行的列: 注意位置，列都是从0开始
        rowcount = sqlite3_column_int(stmt,0);
    }

    if (rowcount==0){
        printf("该账号不存在,登陆失败!\n");
        return -1;
    }
    printf("账号存在，登陆成功!\n");
    return 0;
}
//注册
int back_admin_regist(){
    printf("后端管理员注册!\n");
    BackAdmin admin;
    printf("输入用户名:");
    scanf("%s",admin.adminname);
    printf("输入密码:");
    scanf("%s",admin.password);
    const char * sql = "insert into admin_user (account,password) values (?,?);";
    sqlite3_stmt * stmt;
    int rc = sqlite3_prepare_v2(db,sql,-1,&stmt,NULL);
    if(rc!=SQLITE_OK){
        fprintf(stderr,"back_admin_regist:编译出错了:%s\n", sqlite3_errmsg(db));
        return -1;
    }
    sqlite3_bind_text(stmt,1,admin.adminname,-1,SQLITE_TRANSIENT);
    sqlite3_bind_text(stmt,2,admin.password,-1,SQLITE_TRANSIENT);
    rc = sqlite3_step(stmt);
    if(rc!=SQLITE_DONE){
        printf("注册失败!\n");
        sqlite3_finalize(stmt);
        return -1;
    }
    printf("注册成功!\n");
    sqlite3_finalize(stmt);
    return 0;
}